package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.utils.QiNiuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author wgq
 * @date 2019-10-11 17:06
 */
@RestController
@RequestMapping("/qiniu")
public class QiNiuController {

    /*@Autowired
    private JedisPool jedisPool;*/

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        try {
            //读取原始文件名，其中getOriginalFilename()方法获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            //读取 最后一个点号的索引
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //读取文件后缀
            String suffix = originalFilename.substring(lastIndexOf);
            //使用UUID产生随机文件名，防止同名文件覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            String successFileName = QiNiuUtils.upload2Qiniu(imgFile.getBytes(), fileName);
            if (successFileName != null) {
                //jedispool存储
                //jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES, successFileName);
                //RedisTemplate存储数据到redis。为了使用注解开发
                redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_RESOURCES, successFileName);
                System.out.println("successFileName:" + successFileName);
                return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, successFileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL, "解析文件错误");
        }
        return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
    }
}
